<template>
  <div>
    <Form ref="vuexArticleDetail" :model="vuexArticleDetail" :rules="ruleValidate" :label-width="100">
      <FormItem label="文章图片" prop="title">
        <Button type="primary" icon="ios-search" @click="upload('album')">上传图片</Button>
      </FormItem>

    <FormItem>
      <img v-if="vuexArticleDetail.at_image && vuexArticleDetail.at_image_type!='mp4'" v-for="(item,index) in vuexArticleDetail.at_image"
        :src="item.url" style="width: 70px;height: 70px;border: 1px solid #eeeeee;" />

    </FormItem>


      <FormItem label="正方形封面" prop="title">
        <Button type="primary" icon="ios-search" @click="upload('cover')">上传图片</Button>
      </FormItem>
      <FormItem>
        <img v-if="vuexArticleDetail.au_image && vuexArticleDetail.au_image_type!='mp4'" v-for="(item,index) in vuexArticleDetail.au_image"
          :src="item.url" style="width: 70px;height: 70px;border: 1px solid #eeeeee;" />

      </FormItem>


      <FormItem>
        <quill-editor style='height:500px;' :options="editorOption" @blur="onEditorBlur($event) " v-model="vuexArticleDetail.content" ref="myQuillEditor"
          @focus="onEditorFocus($event)" @ready="onEditorReady($event)" @change="onEditorChange($event)">

        </quill-editor>
      </FormItem>

    </Form>
    <!-- <VueUeditorWrap/> -->
    <Modal v-model="uploadModal" title="图片管理" class="uploadModal-wrap" :closable='isClosable'>
      <!-- 上传组件 -->
      <div>
        <UploadTool :showUpload='showUpload' :optionObj='uploadImgPathList' @getSelectedImgList='getSelectedImgList'>
        </UploadTool>
      </div>
      <div slot="footer">
        <Button @click='cancelUploadModal'>取消</Button>
        <Button type="primary" @click='confirm(uploadType)'>确定</Button>
      </div>

    </Modal>
  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  // import VueUeditorWrap from 'vue-ueditor-wrap'
  import Tables from '_c/tables'
  import {
    initConfig,
    uploadImgPathList
  } from '@/config/global.js'
  // require styles
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  // 上传组件
  import UploadTool from '../../../components/uploadTool/uploadTool.vue'

  import {
    quillEditor,
    Quill
  } from 'vue-quill-editor'

  import ImageResize from 'quill-image-resize-module'

  Quill.register('modules/imageResize', ImageResize)
  export default {
    name: 'tables_page',
    components: {
      Tables,
      quillEditor,
      UploadTool
      // VueUeditorWrap //ueditor富文本编辑器
    },
    created() {
      this.getList()
    
      this.setVuexArticleDetail({
        cover_image: '',
        artical_image:''
      });
    },
    watch: {

    },
    mounted() {
      this.$nextTick(function() {
        // 编辑器
      })
    },
    computed: {
      ...mapState({
        vuexArticleDetail: state => state.article.vuexArticleDetail
      })
    },




    data() {
      // 工具栏配置
      const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
        ['blockquote', 'code-block'], // 引用，代码块

        [{
          header: 1
        }, {
          header: 2
        }], // 标题，键值对的形式；1、2表示字体大小
        [{
          list: 'ordered'
        }, {
          list: 'bullet'
        }], // 列表
        [{
          script: 'sub'
        }, {
          script: 'super'
        }], // 上下标
        [{
          indent: '-1'
        }, {
          indent: '+1'
        }], // 缩进
        [{
          direction: 'rtl'
        }], // 文本方向

        [{
          size: ['small', false, 'large', 'huge']
        }], // 字体大小
        [{
          header: [1, 2, 3, 4, 5, 6, false]
        }], // 几级标题

        [{
          color: []
        }, {
          background: []
        }], // 字体颜色，字体背景颜色
        [{
          font: []
        }], // 字体
        [{
          align: []
        }], // 对齐方式

        ['clean'], // 清除字体样式
        ['image', 'video'] // 上传图片、上传视频
      ]
      let self = this
      return {
        album_imageArr: [],
        cover_image: '',
        initConfig: initConfig,
        uploadImgPathList: uploadImgPathList,
        uploadModal: false,
        // 子组件传递过来
        isClosable: false,
        fromChild: {
          selectedImgList: []
        },
        uploadType: '', // 上传按钮判断
        uploadIndex: 0,
        showUpload: false,
        // wenben
        editorOption: {
          modules: {
            // imageDrop: true,
            imageResize: {
              displayStyles: {
                backgroundColor: 'black',
                border: 'none',
                color: 'white'
              },
              modules: ['Resize', 'DisplaySize', 'Toolbar']
            },

            toolbar: {
              container: toolbarOptions, // 工具栏
              handlers: {
                'image': function(val) {
                  console.log(val)
                  if (val) {
                    self.upload('detail')
                    // document.querySelector('.editor-upload').click()
                  } else {
                    this.quill.format('image', false) // 禁用quill内部上传图片
                  }
                }

              }
            }
          }
          // some quill options
        },
        // emd
        formValidate: {},
        tableData: [],
        ruleValidate: {},

        data: [

        ]

      }
    },
    methods: {
      ...mapMutations([
        'setVuexArticleDetail' // 详情

      ]),




      // 上传
      upload(type, index) {
        // type为上传的类型，‘cover’封面
        this.uploadType = type
        this.uploadIndex = index
        this.uploadModal = true
        this.showUpload = true
      },
      cancelUploadModal() {
        this.uploadModal = false
        this.showUpload = false
      },
      confirm(type) {
        let _this = this;
        if (!this.fromChild.selectedImgList.length) {
          this.$Message.error('请选择图片或者视频!');
          return
        }
        this.uploadModal = false;
        if (type == 'cover') {
          // 封面
          let obj = this.vuexArticleDetail;
          obj.au_image = this.fromChild.selectedImgList[0].url;
          console.log('封面',obj.au_image )
          // obj.au_image_type = this.fromChild.selectedImgList[0].extension;
          obj.au_image_file_name = this.fromChild.selectedImgList[0].path_name;
          // this.setVuexArticleDetail(obj)
          obj.au_image = this.fromChild.selectedImgList.map((res => {
            return {
              url: res.url,
              // extension: res.extension,
              file_name: res.path_name
            }

          }))

        }else if(type=='detail'){
          let quill = this.$refs.myQuillEditor.quill;
          this.fromChild.selectedImgList.forEach(function(cv) {
            let length = quill.selection.savedRange.index
            // 插入图片
            quill.insertEmbed(length, 'image', cv.url)
            //quill.insertEmbed(length, 'video', url)
            // 调整光标到最后
            quill.setSelection(length + 1)

          })
          this.uploadModal = false;
          this.showUpload = false;
        }
        else if (type == 'album') {
          // 相册
          let obj = this.vuexArticleDetail;
          obj.at_image = this.fromChild.selectedImgList[0].url;
          console.log('图片',obj.at_image )
          // obj.at_image_type = this.fromChild.selectedImgList[0].extension;
          obj.at_image_file_name = this.fromChild.selectedImgList[0].path_name;
          this.setVuexArticleDetail(obj)
          obj.at_image = this.fromChild.selectedImgList.map((res => {
            return {
              url: res.url,
              // extension: res.extension,
              file_name: res.path_name
            }

          }))
          console.log(obj)
        }
      },
      getSelectedImgList(e) {
        this.fromChild.selectedImgList = e
      },
      // 列表数据
      getList() {
        let type = 'success'
        // this.$Message[type]({
        //   background: true,

        // });
      },
      // wen
      escapeStringHTML(str) {
        // 转码
        str = str.replace(/&lt;/g, '<')
        str = str.replace(/&gt;/g, '>')
        return str
      },


      onEditorBlur(quill) {

      },
      onEditorFocus(quill) {

      },
      onEditorReady(quill) {

      },
      onEditorChange({
        quill,
        html,
        text
      }) {
        // console.log('editor change!', quill, html, text)
        // console.log(this.escapeStringHTML(html))
        // this.setVuexArticleBasicObj(this.escapeStringHTML(html))

        // this.prodGroupGoodsDetailObj =this.escapeStringHTML(html);
      },
      // end
      handleEdit(row, index) {
        this.editName = row.name
        this.editAge = row.age
        this.editAddress = row.address
        this.editBirthday = row.birthday
        this.editIndex = index
      },
      handleSave(index) {
        this.data[index].name = this.editName
        this.data[index].age = this.editAge
        this.data[index].birthday = this.editBirthday
        this.data[index].address = this.editAddress
        this.editIndex = -1
      },
      getBirthday(birthday) {
        const date = new Date(parseInt(birthday))
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        return `${year}-${month}-${day}`
      },
      change(status) {
        this.$Message.info('开关状态：' + status)
      }
    }

  }
</script>

<style lang="scss">
  @import "./article-detail";
</style>
